package data;

import java.util.ArrayList;
import java.util.Iterator;
import ui.*;
import commProtocol.*;

public class ListContacts implements Observable {

	private CollectionContactTarget contacts;
        private ArrayList<Observer> listObserver;

	
	public ListContacts(CollectionContactTarget c){
		contacts= c;
                listObserver = new ArrayList<Observer>();
        }
	
	public void addContact(Contact contact){
		contacts.add(contact);
                notify(contact,true);
        }
	
	public void removeContact(String name){
                notify(contacts.get(name),false);
		contacts.remove(name);
	}
	
	public void removeAllContacts(){
                
                // il faut updater pour chaque élément de la liste
                Iterator<Contact> it = contacts.iterator();

                while(it.hasNext()){
			notify(it.next(),false);
		}

                //suppression réelle des éléments de la liste
		contacts.removeAll();
	}
	
	public Contact getContact(String name){
		return contacts.get(name);
	}
	
	public Contact getContactByAddress(String address){
		Contact c = new Contact("", "");
		Iterator<Contact> it = contacts.iterator();
		
		while(it.hasNext()){
			c = it.next();
			if (c.getIp() == address){
				return c;
			}
		}
		System.out.println("Le contact n'existe pas, adresse invalide\n");
		
		//on renvoie alors un contact vide
		c.setLogin("");
		c.setIp("");
		return c;
		
	}




    public void addObserver(Observer obs) {
        this.listObserver.add(obs);
    }

    public void notify(Contact contact, boolean action) {
        for(Observer obs : this.listObserver )
            obs.update(contact, action);
    }

    public void delObserver(Observer obs) {
        this.listObserver.remove(obs);
    }

	
	
	
	
}
